package com.atguigu.tingshu.user.login;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.atguigu.tingshu.account.client.UserAccountFeignClient;
import com.atguigu.tingshu.common.constant.RabbitConstant;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.user.mapper.UserInfoMapper;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@LoginBean
public class WxLogin implements ILogin{

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private WxMaService wxMaService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private UserAccountFeignClient userAccountFeignClient;

    @Override
    public Map<String, String> login(LoginVo loginVo) {
        // 调用微信的远程接口获取openId
        String openid = null;
        try {
            WxMaJscode2SessionResult sessionInfo = this.wxMaService.getUserService().getSessionInfo(loginVo.getCode());
            openid = sessionInfo.getOpenid();
            if (StringUtils.isBlank(openid)){
                throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
            }
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }

        // 根据openId查询mysql数据库中的用户信息
        UserInfo userInfo = this.userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getWxOpenId, openid));

        // 判断用户信息是否为空，如果为空则隐式注册
        if (userInfo == null){
            userInfo = new UserInfo();
            userInfo.setWxOpenId(openid);
            userInfo.setNickname("游客" + IdWorker.getIdStr());
            userInfo.setAvatarUrl("https://pics0.baidu.com/feed/0dd7912397dda144d4368c78e96113af0df48625.jpeg?token=a9d4959bb5fd5ea3c077295bb84ed954");
            userInfo.setStatus("1");
            this.userInfoMapper.insert(userInfo);
            // 初始化账户信息
//            this.userAccountFeignClient.saveAccount(userInfo.getId());
            this.rabbitTemplate.convertAndSend(RabbitConstant.USER_EXCHANGE, RabbitConstant.USER_REGISTER_RK, userInfo.getId());
//			int i = 1/0;
        }

        // 生成token唯一标识
        String token = UUID.randomUUID().toString();
        // 以token作为key，以用户信息作为value缓存到redis
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, userInfoVo);
        this.redisTemplate.opsForValue().set(RedisConstant.USER_LOGIN_KEY_PREFIX + token, userInfoVo, RedisConstant.USER_LOGIN_KEY_TIMEOUT, TimeUnit.SECONDS);

        // 把token返回给前端
        Map<String, String> map = new HashMap<>();
        map.put("token", token);
        return map;
    }
}
